package com.telecom.service.impl;

import com.telecom.common.convention.errorcode.BaseErrorCode;
import com.telecom.common.convention.exception.ClientException;
import com.telecom.common.convention.exception.ServiceException;
import com.telecom.common.convention.result.PageDTO;
import com.telecom.mapper.MealMapper;
import com.telecom.pojo.dto.admin.meal.AddMealDTO;
import com.telecom.pojo.dto.admin.meal.ModifyMealDTO;
import com.telecom.pojo.dto.admin.meal.AdminMealPageQueryRequestDTO;
import com.telecom.pojo.dto.user.meal.UserMealPageQueryRequestDTO;
import com.telecom.pojo.entity.Meal;
import com.telecom.pojo.vo.admin.setmeal.AdminMealDetailVO;
import com.telecom.pojo.vo.admin.setmeal.MealPageVO;
import com.telecom.pojo.vo.user.meal.MealItemVO;
import com.telecom.pojo.vo.user.meal.UserMealDetailVO;
import com.telecom.service.MealService;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 餐品服务实现类
 */
@Service
@Slf4j
public class MealServiceImpl implements MealService {

    @Resource
    private MealMapper mealMapper;

    @Override
    public void addMeal(AddMealDTO addMealDTO) {
        log.info("新增餐品，餐品信息：{}", addMealDTO);
        
        // 检查是否提前一天添加套餐
        LocalDate mealDate = addMealDTO.getDate();
        LocalDate tomorrow = LocalDate.now().plusDays(1);
        if (mealDate.isBefore(tomorrow)) {
            throw new ClientException("只能提前一天添加套餐", BaseErrorCode.CLIENT_ERROR);
        }
        
        // 构建餐品实体
        Meal meal = Meal.builder()
                .name(addMealDTO.getName())
                .description(addMealDTO.getDescription())
                .price(addMealDTO.getPrice())
                .mealType(addMealDTO.getMealType())
                .date(addMealDTO.getDate())
                .imageUrl(addMealDTO.getImageUrl())
                .stock(addMealDTO.getStock())
                .isAvailable(true)  // 默认可用
                .salesCount(0)   // 初始销量为0
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();

        try {
            mealMapper.insert(meal);
        }
        catch (Exception e){
            throw new ServiceException("新增餐品失败", BaseErrorCode.SERVICE_ERROR);
        }
        
        log.info("新增餐品成功，餐品ID：{}", meal.getId());
    }

    @Override
    public void deleteMeals(List<Long> ids) {
        log.info("批量删除餐品，餐品ID列表：{}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new ClientException("餐品ID列表不能为空", BaseErrorCode.CLIENT_ERROR);
        }

        try {
            mealMapper.deleteBatchByIds(ids);
        }
        catch (Exception e){
            throw new ClientException("删除餐品失败", BaseErrorCode.SERVICE_ERROR);
        }

    }

    @Override
    public void updateMeal(ModifyMealDTO modifyMealDTO) {
        log.info("修改餐品，餐品信息：{}", modifyMealDTO);
        
        // 检查是否提前一天修改套餐
        LocalDate mealDate = modifyMealDTO.getDate();
        LocalDate tomorrow = LocalDate.now().plusDays(1);
        if (mealDate.isBefore(tomorrow)) {
            throw new ClientException("只能提前一天修改套餐", BaseErrorCode.CLIENT_ERROR);
        }

        
        // 构建更新的餐品实体
        Meal meal = Meal.builder()
                .id(modifyMealDTO.getId())
                .name(modifyMealDTO.getName())
                .description(modifyMealDTO.getDescription())
                .price(modifyMealDTO.getPrice())
                .mealType(modifyMealDTO.getMealType())
                .date(modifyMealDTO.getDate())
                .imageUrl(modifyMealDTO.getImageUrl())
                .stock(modifyMealDTO.getStock())
                .updateTime(LocalDateTime.now())
                .build();

        try {
            mealMapper.updateById(meal);
        }
        catch (Exception e){
            throw new ServiceException("修改餐品失败", BaseErrorCode.SERVICE_ERROR);
        }
        
        log.info("修改餐品成功，餐品ID：{}", modifyMealDTO.getId());
    }

    @Override
    public AdminMealDetailVO getMealById(Long id) {
        log.info("根据ID查询餐品详情，餐品ID：{}", id);
        Meal meal;
        try {
            meal = mealMapper.selectById(id);
        }
        catch (Exception e){
            throw new ClientException("餐品不存在", BaseErrorCode.CLIENT_ERROR);
        }
        
        // 转换为VO
        AdminMealDetailVO adminMealDetailVO = new AdminMealDetailVO();
        BeanUtils.copyProperties(meal, adminMealDetailVO);
        
        // 设置餐品状态，将Boolean转换为String
        adminMealDetailVO.setStatus(meal.getIsAvailable() ? 1 : 0);
        
        // 设置图片字段映射
        adminMealDetailVO.setImage(meal.getImageUrl());
        
        // 设置销量字段映射
        adminMealDetailVO.setSales(meal.getSalesCount());
        
        log.info("查询餐品详情成功，餐品名称：{}", meal.getName());
        return adminMealDetailVO;
    }

    @Override
    public PageDTO<MealPageVO> page(AdminMealPageQueryRequestDTO queryRequest) {
        log.info("分页查询餐品，查询条件：{}", queryRequest);
        
        // 启用PageHelper分页
        PageHelper.startPage(queryRequest.getPageNo(), queryRequest.getPageSize());
        
        // 查询数据
        List<MealPageVO> records = mealMapper.selectPageByCondition(queryRequest);
        
        // 创建PageInfo并转换为PageDTO
        PageInfo<MealPageVO> pageInfo = new PageInfo<>(records);
        PageDTO<MealPageVO> pageResult = new PageDTO<>(pageInfo.getTotal(), (long) pageInfo.getPages(), pageInfo.getList());
        
        log.info("分页查询餐品成功，总数：{}，当前页数据量：{}", pageInfo.getTotal(), records.size());
        return pageResult;
    }

    @Override
    public void updateStatus(Long id, Boolean status) {
        log.info("更新餐品状态，餐品ID：{}，状态：{}", id, status);

        
        // 构建更新实体
        Meal meal = Meal.builder()
                .id(id)
                .isAvailable(status)
                .updateTime(LocalDateTime.now())
                .build();

        try {
            mealMapper.updateById(meal);
        }
        catch (Exception e){
            throw new ServiceException("更新餐品状态失败", BaseErrorCode.SERVICE_ERROR);
        }
        
        log.info("更新餐品状态成功，餐品ID：{}", id);
    }

    @Override
    public PageDTO<MealItemVO> userPage(UserMealPageQueryRequestDTO queryRequest) {
        log.info("用户端套餐分页查询：{}",queryRequest);

        // 启用PageHelper分页
        PageHelper.startPage(queryRequest.getPageNo(), queryRequest.getPageSize());
        List<MealItemVO> records = mealMapper.userSelectPageByCondition(queryRequest);

        // 创建PageInfo并转换为PageDTO
        PageInfo<MealItemVO> pageInfo = new PageInfo<>(records);
        PageDTO<MealItemVO> userPageResult = new PageDTO<>(pageInfo.getTotal(), (long) pageInfo.getPages(), pageInfo.getList());

        log.info("用户套餐分页查询成功，总数：{}，当前页数据量：{}", pageInfo.getTotal(), records.size());
        return userPageResult;
    }

    @Override
    public UserMealDetailVO userGetMealDetailById(Long id) {
        Meal meal;
        try {
            meal = mealMapper.selectById(id);
        } catch (Exception e) {
            throw new ClientException("餐品不存在", BaseErrorCode.CLIENT_ERROR);
        }
        UserMealDetailVO userMealDetailVO = new UserMealDetailVO();
        BeanUtils.copyProperties(meal,userMealDetailVO);

        log.info("用户查询套餐详情成功，套餐名称：{}", meal.getName());

        return userMealDetailVO;
    }
}